<template>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :title="!form.id ? $t('add') : $t('update')"
    :visible.sync="visible"
    width="80vw"
  >
    <el-form
      :model="form"
      :rules="dataRule"
      label-width="120px"
      ref="dataForm"
      v-loading="loading"
    >
      <el-form-item
        prop="cityId"
        label="城市">
        <!--                            v-model="dataForm.cityId"-->
        <el-select
          clearable
          placeholder="城市"
          v-model="form.cityId">
          <el-option
            :key="'city-' + city.id"
            :label="city.name"
            :value="city.id"
            v-for="city in cities"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        prop="foodStoryId"
        label="美食故事">
        <!--                            v-model="dataForm.cityId"-->
        <el-select
          clearable
          placeholder="美食故事"
          v-model="form.foodStoryId">
          <el-option
            :key="'foodstory-' + foodStory.id"
            :label="foodStory.title"
            :value="foodStory.id"
            v-for="foodStory in foodStories"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        label="推荐产品"
        prop="sn8">
        <el-select
          class="product-select"
          :remote="getProducts"
          placeholder="选择产品"
          v-model="form.sn8"
        >
          <el-option
            :key="item.sn8"
            :label="item.sn8"
            :value="item.sn8"
            v-for="item in products"
          >
            <span>{{ item.recommendProductText }}</span>
            <span v-if="item.sn8 && item.sn8.length > 0">({{ item.sn8 }})</span>
          </el-option>
        </el-select>
      </el-form-item>
      <!--      <el-form-item prop="sn8" label="设备SN8">-->
      <!--        <sn8-select :sn8.sync="form.sn8"></sn8-select>-->
      <!--      </el-form-item>-->
      <el-form-item
        label="图片"
        prop="url">
        <div class="image-desc">
          图片尺寸：(一倍图：244*372；二倍图：488*744)
        </div>
        <el-upload
          :file-list="imgFileList"
          :limit="1"
          :multiple="false"
          :on-exceed="handleImgFileExceed"
          :on-preview="handleImgPreview"
          :on-remove="onImgRemoved"
          :on-success="onImgUploadSuccess"
          accept="image/png, image/jpeg"
          action="http://47.106.93.196:8200/cloud-menu/midea/menu/file/upload"
          list-type="picture-card"
        >
          <i class="el-icon-plus"/>
        </el-upload>
      </el-form-item>
    </el-form>

    <template slot="footer">
      <el-button
        :loading="requesting"
        @click="visible = false">{{
          $t("cancel")
        }}</el-button>
      <el-button
        :loading="requesting"
        @click="dataFormSubmitHandle()"
        type="primary"
      >{{ $t("confirm") }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import mixinViewModule from '@/mixins/mike.view-module'
import Sn8Select from '../../../../components/sn8.select'
export default {
  name: 'FoodcardAddOrUpdate',
  components: { Sn8Select },
  mixins: [mixinViewModule],
  data () {
    return {
      visible: false,
      loading: false,
      requesting: false,
      cities: [],
      foodStories: [],
      products: [],
      imgFileList: [],

      previewImgUrl: '',
      previewDialogVisible: false,
      form: {
        cityId: '',
        describ: '',
        ext: '',
        flag: 0,
        foodStoryId: '',
        id: '',
        sn8: '',
        totalCounts: 0,
        url: ''
      }
    }
  },
  computed: {
    dataRule () {
      return {
        // title: [
        //     {
        //         required: true,
        //         message: this.$t('validate.required'),
        //         trigger: 'blur'
        //     }
        // ],
        // menuId: [
        //     {
        //         required: true,
        //         message: this.$t('validate.required'),
        //         trigger: 'blur'
        //     }
        // ]
      }
    }
  },
  methods: {
    reset () {
      this.$refs['dataForm'] && this.$refs['dataForm'].resetFields()
      this.imgFileList = []
      this.form = {
        cityId: '',
        describ: '',
        ext: '',
        flag: 0,
        foodStoryId: '',
        id: '',
        sn8: '',
        totalCounts: 0,
        url: ''
      }
    },
    init () {
      this.visible = true

      this.$nextTick(() => {
        if (this.form.id && this.form.id.length > 0) {
          if (this.form.url && this.form.url.length > 0) {
            this.imgFileList = [{ name: this.form.url, url: this.form.url }]
          }
        }

        this.getAllFoodStory()
        this.getCities()
        this.getProducts()

        // this.getRecipes()

        // Promise.race([ ])
      })
    },
    /*
     * Img event
     * */

    handleImgFileExceed () {
      this.$message.warning(`只能设置一张图片哦`)
    },

    handleImgPreview () {
      this.previewImgUrl = this.form.url
      this.previewDialogVisible = true
    },
    onImgRemoved () {
      this.form.url = ''
    },
    onImgUploadSuccess (response) {
      if (response.code !== 200) {
        this.form.url = ''
        return
      }
      this.form.url = response.data
    },
    getCities () {
      this.$http
        .post(`${this.mikeNetworkBase}midea/menu/foodmap/common/citys/`)
        .then(({ data: res }) => {
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }
          this.cities = res.data
        })
    },
    async getProducts () {
      this.$http
        .post(
          `${this.mikeNetworkBase}midea/menu/foodmap/foodstorys/getallproduct`
        )
        .then(({ data: res }) => {
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }

          this.products = res.data
        })
    },

    getAllFoodStory () {
      this.$http
        .post(`${this.mikeNetworkBase}midea/menu/foodmap/foodstorys/getall`, {
          pageSize: 1000,
          currentPage: 1
        })
        .then(({ data: res }) => {
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }
          console.log(res.data)
          this.foodStories = res.data
        })
    },
    dataFormSubmitHandle () {
      this.$refs['dataForm'].validate(valid => {
        if (!valid) {
          return false
        }
        if (this.requesting) {
          return
        }
        let params = {
          ...this.form
          // status: this.form.status ? 1 : 0
        }
        // console.log(params)
        this.requesting = true
        this.$http
          .post(
            `${this.mikeNetworkBase}midea/menu/foodmap/foodcards/save`,
            params
          )
          .then(({ data: res }) => {
            if (res.code !== 200) {
              return this.$message.error(res.msg)
            }
            this.$message({
              message: this.$t('prompt.success'),
              type: 'success',
              duration: 500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          })
          .catch(() => {})
          .finally(() => {
            this.requesting = false
          })
      })
    }
  }
}
</script>

<style scoped lang="less">
.image-desc {
  color: #999999;
  margin-bottom: 10px;
}
</style>
